﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using DAO;
using Microsoft.Win32;

namespace QLKS
{
    public partial class frmConnect : DevExpress.XtraEditors.XtraForm
    {
        public frmConnect()
        {
            InitializeComponent();
        }
        private const string dataBaseName = "QLKSAN";
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (cbbAuthen.SelectedIndex == 0)
                ConnectionString.WriteFile(txtServer.Text, cbbDatabase.Text, "", "");
            else ConnectionString.WriteFile(txtServer.Text, cbbDatabase.Text, txtUser.Text, txtPass.Text);
            Close();
        }
        static string ServerName()
        {
            RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server");
            String[] instances = (String[])rk.GetValue("InstalledInstances");
            if (instances.Length > 0)
            {
               foreach (String element in instances)
               {
                  if (element == "MSSQLSERVER")
                    return Environment.MachineName;
                  else
                      return String.Format(@"{0}\{1}", Environment.MachineName, element);
               }
            }
            return @"./SQLEXPRESS";
        }
        private void frmConnect_Load(object sender, EventArgs e)
        {
            txtServer.Text=ServerName();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnTestConnect_Click(object sender, EventArgs e)
        {
            //Quyền Windows
            if (cbbAuthen.SelectedIndex == 0)
            {
                //AttachDbFilename=|DataDirectory|CNPM.mdf;Database=CNPM; Trusted_Connection=Yes;
                cbbDatabase.Properties.Items.Clear();
                string a = String.Format("Data Source={0};AttachDbFilename=|DataDirectory|{1}.mdf;Database={1}; Trusted_Connection=Yes;", txtServer.Text, dataBaseName);
                SqlConnection con = new SqlConnection(a);
                SqlCommand cmd = new SqlCommand("SP_DATABASES", con);
                //SP_DATABASES là một store procedure có sẵn của sql server để lấy ra tất cả csdl trong sql server
                SqlDataReader reader;
                try
                {
                    con.Open();
                    reader = cmd.ExecuteReader();
                    //Bnguoidung.AttachFile();
                    while (reader.Read())
                    {
                        cbbDatabase.Properties.Items.Add(reader[0].ToString());
                    }
                    cbbDatabase.Enabled = true;
                    cbbDatabase.Text = dataBaseName;
                    MessageBox.Show("Kết nối thành công!", "SUCCESSED", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch(SqlException ex)
                {
                    MessageBox.Show("Lỗi, vui lòng thử lại!\n"+ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    if (con.State == ConnectionState.Open)
                        con.Close();

                    con.Dispose();
                    cmd.Dispose();
                }
            }

            //Quyền SQL Server
            if (cbbAuthen.SelectedIndex == 1)
            {
                cbbDatabase.Properties.Items.Clear();
                SqlConnection con = new SqlConnection(String.Format("Data Source={0};Initial Catalog=master;User Id={1};Password={2};", txtServer.Text, txtUser.Text, txtPass.Text));
                SqlCommand cmd = new SqlCommand("SP_DATABASES", con);
                SqlDataReader reader;

                try
                {
                    con.Open();
                    reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        cbbDatabase.Properties.Items.Add(reader[0].ToString());
                    }
                    cbbDatabase.Enabled = true;
                    MessageBox.Show("Kết nối thành công!", "SUCCESSED", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch
                {
                    MessageBox.Show("Lỗi, vui lòng thử lại!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    if (con.State == ConnectionState.Open)
                        con.Close();

                    con.Dispose();
                    cmd.Dispose();
                }
            }
        }

        private void cbbAuthen_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbbAuthen.SelectedIndex == 0)
            {
                txtUser.Enabled = false;
                txtPass.Enabled = false;
            }
            else
            {
                txtUser.Enabled = true;
                txtPass.Enabled = true;
            }
        }

        private void cbbDatabase_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnOk.Enabled = true;
        }
    }
}